package com.lwf.fatapi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.lwf.fatapi.entities.SysRole;
import com.lwf.fatapi.exception.BusinessException;
import com.lwf.fatapi.mapper.SysRoleMapper;
import com.lwf.fatapi.mapper.SysUserRoleMapper;
import com.lwf.fatapi.service.SysRoleService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

import static com.lwf.fatapi.entity.table.SysRoleTableDef.SYS_ROLE;

/**
 * 系统角色服务实现类
 *
 * @author lwf
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    public boolean createRole(SysRole role) {
        // 检查角色编码是否已存在
        SysRole existRole = roleMapper.selectByRoleCode(role.getRoleCode());
        if (existRole != null) {
            throw new BusinessException("角色编码已存在");
        }

        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        role.setCreateBy(getCurrentUserId());
        role.setIsDeleted(0);
        if (role.getStatus() == null) {
            role.setStatus(1);
        }

        return roleMapper.insert(role) > 0;
    }

    @Override
    public boolean updateRole(Long id, SysRole role) {
        SysRole existRole = roleMapper.selectOneById(id);
        if (existRole == null) {
            throw new BusinessException("角色不存在");
        }

        // 检查角色编码是否已被其他角色使用
        SysRole codeRole = roleMapper.selectByRoleCode(role.getRoleCode());
        if (codeRole != null && !codeRole.getId().equals(id)) {
            throw new BusinessException("角色编码已存在");
        }

        existRole.setRoleName(role.getRoleName());
        existRole.setRoleCode(role.getRoleCode());
        existRole.setDescription(role.getDescription());
        if (role.getStatus() != null) {
            existRole.setStatus(role.getStatus());
        }
        existRole.setUpdateTime(LocalDateTime.now());
        existRole.setUpdateBy(getCurrentUserId());

        return roleMapper.update(existRole) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRole(Long id) {
        SysRole role = roleMapper.selectOneById(id);
        if (role == null) {
            throw new BusinessException("角色不存在");
        }

        // 逻辑删除角色
        role.setIsDeleted(1);
        role.setUpdateTime(LocalDateTime.now());
        role.setUpdateBy(getCurrentUserId());

        boolean result = roleMapper.update(role) > 0;

        // 删除角色关联的用户角色关系
        if (result) {
            userRoleMapper.deleteByRoleId(id);
        }

        return result;
    }

    @Override
    public SysRole getRoleById(Long id) {
        return roleMapper.selectOneByQuery(
                QueryWrapper.create().where(SYS_ROLE.ID.eq(id).and(SYS_ROLE.IS_DELETED.eq(0)))
        );
    }

    @Override
    public SysRole getRoleByCode(String roleCode) {
        return roleMapper.selectByRoleCode(roleCode);
    }

    @Override
    public Page<SysRole> getRolePage(int pageNo, int pageSize, String keyword) {
        QueryWrapper query = QueryWrapper.create()
                .where(SYS_ROLE.IS_DELETED.eq(0));

        if (StrUtil.isNotBlank(keyword)) {
            query.and(SYS_ROLE.ROLE_NAME.like(keyword)
                    .or(SYS_ROLE.ROLE_CODE.like(keyword))
                    .or(SYS_ROLE.DESCRIPTION.like(keyword)));
        }

        query.orderBy(SYS_ROLE.CREATE_TIME.desc());

        return roleMapper.paginate(pageNo, pageSize, query);
    }

    @Override
    public List<SysRole> getAllRoles() {
        return roleMapper.selectListByQuery(
                QueryWrapper.create().where(SYS_ROLE.IS_DELETED.eq(0).and(SYS_ROLE.STATUS.eq(1)))
                        .orderBy(SYS_ROLE.CREATE_TIME.desc())
        );
    }

    @Override
    public List<SysRole> getRolesByUserId(Long userId) {
        return roleMapper.selectRolesByUserId(userId);
    }

    @Override
    public boolean toggleRoleStatus(Long id, Integer status) {
        SysRole role = roleMapper.selectOneById(id);
        if (role == null) {
            throw new BusinessException("角色不存在");
        }

        role.setStatus(status);
        role.setUpdateTime(LocalDateTime.now());
        role.setUpdateBy(getCurrentUserId());

        return roleMapper.update(role) > 0;
    }

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        try {
            return Long.valueOf(StpUtil.getLoginId().toString());
        } catch (Exception e) {
            return null;
        }
    }
}
